const formatTime = date => {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()

  return [year, month, day].map(formatNumber).join('/') + ' ' + [hour, minute, second].map(formatNumber).join(':')
}

const formatNumber = n => {
  n = n.toString()
  return n[1] ? n : '0' + n
}

const formatHtml = content => {
  content = content.replace(/\<img/gi, '<img style="width:100% !important;height:auto !important;margin:0;display:flex;" ');
  content = content.replace(/style="/gi, 'style="max-width:100% !important;table-layout:fixed;word-wrap:break-word;word-break;break-all;');
  content = content.replace(/\<table/gi, '<table style="table-layout:fixed;word-wrap:break-word;word-break;break-all;" ');
  content = content.replace(/\<td/gi, '<td  cellspacing="0" cellpadding="0" border="0" style="display:block;vertical-align:top;margin: 0px; padding: 0px; border: 0px;outline-width:0px;" ');
  content = content.replace(/width=/gi, 'sss=');
  content = content.replace(/height=/gi, 'sss=');
  content = content.replace(/ \/\>/gi, ' style="max-width:100% !important;height:auto !important;margin:0;display:block;" \/\>');
  return content;
}

const endOfStartTime = (startTime, endTime) =>{
  let result = {
    day: '00',
    hou: '00',
    min: '00',
    sec: '00'
  }
  if (endTime - startTime > 0) {
    let time = (endTime - startTime) / 1000;
    // 获取天、时、分、秒
    let day = parseInt(time / (60 * 60 * 24));
    let hou = parseInt(time % (60 * 60 * 24) / 3600);
    let min = parseInt(time % (60 * 60 * 24) % 3600 / 60);
    let sec = parseInt(time % (60 * 60 * 24) % 3600 % 60);
    result = {
      day: `${timeFormat(day)}`,
      hou: `${timeFormat(hou)}`,
      min: `${timeFormat(min)}`,
      sec: `${timeFormat(sec)}`
    }
  }
  return result
}

// 小于10的格式化函数
const timeFormat = (times) => {
  return times < 10 ? '0' + times : times;
}

const dateToTimestamp = (dateStr)=> {
  if (!dateStr) {
    return ''
  }
  let newDataStr = dateStr.replace(/\.|\-/g, '/')
  let date = new Date(newDataStr);
  let timestamp = date.getTime();
  return timestamp
}

/**
 * 手机号正则校验
 */
const checkPhoneNumber = (phoneNumber) => {
  var regexp = /^[1]([3-9])[0-9]{9}$/
  return regexp.test(phoneNumber)
}

/**
 * 用户名正则校验
 */
const checkUserName = (userName) => {
  var regexp = /^([a-zA-Z0-9_]{4,16})$/
  return regexp.test(userName)
}
// 检查是否授权
const checkAuthInfo = (fn, unNeedAuth) => {
  if (wx.getStorageSync('loginResult').userId) {
    fn()
  } else if (!unNeedAuth) {
    wx.hideLoading()
    wx.navigateTo({
      url: '/pages/login/login'
    })
  }
}

module.exports = {
  dateToTimestamp: dateToTimestamp,
  formatTime: formatTime,
  formatHtml: formatHtml,
  endOfStartTime: endOfStartTime,
  checkPhoneNumber: checkPhoneNumber,
  checkUserName: checkUserName,
  checkAuthInfo: checkAuthInfo
}
